package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"product/global/model"
	"product/internal/svc"
	"product/product"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}
func (l *ProductListLogic) ProductList(in *product.ProductListRequest) (*product.ProductListResponse, error) {
	// todo: add your logic here and delete this line
	size := 10
	page := in.Page
	var Res product.ProductListResponse
	key := fmt.Sprintf("prout_find:%s:%s:%d", in.Class, in.Title, in.Page)
	ok := model.RDB.Exists(model.Ctx, key).Val()
	if ok == 0 {
		var products []*model.ProductData
		db := model.DB.Model(model.Product{}).Limit(size).Offset((int(page) - 1) * size)
		db = db.Joins("join brand on product.brand_id = brand.brand_id")
		db = db.Joins("join category on product.category_id = category.category_id")
		db = db.Where("product.status = '1'")
		if in.Class != "" {
			db = db.Where("category.category_name like ?", "%"+in.Class+"%")
		}
		if in.Title != "" {
			db = db.Where("product.name like ?", "%"+in.Title+"%")
		}
		db = db.Select("product.*,brand.brand_name as brand,category.category_name as category")
		db.Find(&products)
		for _, data := range products {
			var res = product.Products{
				ProductName:  data.Name,
				ProductId:    int64(data.ProductId),
				ProductPrice: float32(data.Price),
				ProductUrl:   data.ImgUrl,
				ProductClass: data.Category,
			}
			Res.Produces = append(Res.Produces, &res)
		}
		data, _ := json.Marshal(Res)
		model.RDB.Set(model.Ctx, key, string(data), 15*time.Minute)
	} else {
		data := model.RDB.Get(model.Ctx, key).Val()
		json.Unmarshal([]byte(data), &Res)
	}

	return &product.ProductListResponse{
		Produces: Res.Produces,
	}, nil
}
